package test.yj;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.*;

/**
 * Created by 1emontree on 2017/8/14.
 */
public class OkHttpDownload {
    //将文件写入E盘
    public void okHttpPictureGet(byte[] img, String fileName) throws IOException {
        try {
            //separator=="/",相当于分隔符
            File file = new File("E://Test2" + File.separator + fileName);
            FileOutputStream fileOut = new FileOutputStream(file);
            fileOut.write(img);
            fileOut.flush();
            fileOut.close();
            System.out.println("图片已经写入到E盘Test1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取文件
    public static byte[] readInputStream(InputStream instream) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 5];
        int len;
        while ((len = instream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        instream.close();
        return output.toByteArray();
    }

    //从URL获取文件
    public byte[] getImg(String strUrl) throws IOException {
        try {
            //设置Fiddler配置
            System.setProperty("http.proxyHost", "127.0.0.1");
            System.setProperty("https.proxyHost", "127.0.0.1");
            System.setProperty("http.proxyPort", "8888");
            System.setProperty("https.proxyPort", "8888");
            OkHttpClient okHttp = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(strUrl)
                    .addHeader("Referer", "http://img.mmjpg.com/small/2016/656_s.jpg")
                    .build();
            //request.header("http://img.mmjpg.com/small/2016/656_s.jpg");
            Response response = okHttp.newCall(request).execute();
            //response.header("Referer","http://img.mmjpg.com/small/2016/656_s.jpg");
            if (response.isSuccessful()) {
                System.out.println(response.code());
            } else {
                response.body().close();
                throw new IOException("Unexpected code " + response);
            }
            InputStream input = response.body().byteStream();
            byte[] b = readInputStream(input);
            return b;
        } catch (Exception e) {
            System.out.println("没有妹子图片，自动切换URL");
            e.printStackTrace();

        }
        return null;
    }
}

